<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>发起http请求</title>
    <style type="text/css">
      p {
        display: inline;
      }
    </style>
  </head>
  <body>
    <div>
      <button id="btn1">XHR请求</button>
      <button id="btn2">Fetch请求</button>
      <div>
        <span>xhr请求结果：</span>
        <p id="xhr_resp"></p>
      </div>
      <div>
        <span>fetch请求结果：</span>
        <p id="fetch_resp"></p>
      </div>
    </div>
  </body>
  <script>
    const method = "GET";
    let btn1 = document.getElementById("btn1");
    let btn2 = document.getElementById("btn2");
    let xhr_resp = document.getElementById("xhr_resp");
    let fetch_resp = document.getElementById("fetch_resp");
    btn1.onclick = () => {
      let xhr = new XMLHttpRequest();
      xhr.open(
        method,
        "https://www.daived.com/api/front/blog/article/query/one?id=18"
      );
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.responseType = "json";
      xhr.onload = () => {
        xhr_resp.textContent = xhr.response.data.title;
      };
      xhr.send();
    };
    btn2.onclick = () => {
      fetch("https://www.daived.com/api/front/blog/article/query/one?id=19", {
        method: method,
      })
        .then((response) => {
          return response.json();
        })
        .then((json) => {
          fetch_resp.textContent = json.data.title;
        });
    };
  </script>
</html>
